package com.genreate.util.pay.wx.controller;

import com.genreate.util.pay.wx.config.WxPayConfig;
import com.genreate.util.pay.wx.domain.WxPayNotifyInfo;
import com.genreate.util.pay.wx.util.WxPaySignatureValidator;
import com.wechat.pay.java.core.notification.Notification;
import com.wechat.pay.java.core.util.GsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * ES-操作
 *
 * @author ruoyi
 * @date 2024-12-10
 */
@RestController
public class WxController {
    /**
     * 处理微信支付回调通知
     */
    @PostMapping("/wxpay/callback")
    public ResponseEntity<Object> handleCallback(
            @RequestHeader("Wechatpay-Serial") String serial,
            @RequestHeader("Wechatpay-Signature") String signature,
            @RequestHeader("Wechatpay-Timestamp") String timestamp,
            @RequestHeader("Wechatpay-Nonce") String nonce,
            @RequestBody String requestBody) {

        // 1. 执行验签逻辑
        boolean verifySuccess;
        try {
            verifySuccess = WxPaySignatureValidator.validateSignature(
                    serial, signature, timestamp, nonce, requestBody,
                    "微信支付公钥内容", "平台证书内容"
            );
        } catch (Exception e) {
            // 验签过程中发生异常（如证书无效、格式错误等），视为验签失败
            verifySuccess = false;
        }

        // 2. 根据验签结果应答
        if (verifySuccess) {
            // 验签通过：返回200/204，无响应体
            Notification wxPayCallback = GsonUtil.getGson().fromJson(requestBody, Notification.class);

            // 获取解密后的通知内容
            String notifyJson = WxPaySignatureValidator.decrypt(WxPayConfig.apiV3Key, nonce, wxPayCallback.getResource());

            // 解析通知内容
            WxPayNotifyInfo wxPayNotifyInfo = GsonUtil.getGson().fromJson(notifyJson, WxPayNotifyInfo.class);

            return ResponseEntity.status(HttpStatus.OK).body(null);
        } else {
            // 验签失败：返回4XX/5XX，带错误信息
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("code", "FAIL");
            errorResponse.put("message", "验签失败：签名不匹配或参数无效");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
        }
    }
}

